﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace DotNETX.Business.Module
{
    public abstract class BusinessModule : IBusinessModule
    {
        protected string _name;
        public virtual string Name
        {
            get
            {
                if (_name != null) return _name;
                return BLOInstance == null ? null : BLOInstance.GetType().FullName;
            }
            set { _name = value; }
        }

        public virtual object BLOInstance { get; protected set; }

        public abstract void Initial();

        public virtual string Invoke(string func, string[] args)
        {
            if (BLOInstance == null) throw new Exception("Business module haven't been initialized！");
            object retVal = null;

            int args_len = args == null ? 0 : args.Length;

            MethodInfo mi = null;
            ParameterInfo[] pis = null;
            MethodInfo[] mis = BLOInstance.GetType().GetMethods();
            foreach (var m in mis)
            {
                pis = m.GetParameters();
                if (m.Name == func && pis.Length == args_len)
                {
                    mi = m;
                    break;
                }
            }
            if (null == mi) throw new ArgumentException("Invalid invoke!");

            object[] argis = new object[args_len];
            for (int i = 0; i < args_len; i++)
            {
                argis[i] = Newtonsoft.Json.JsonConvert.DeserializeObject(args[i], pis[i].ParameterType);
            }

            if (args_len == 0)
            {
                retVal = mi.Invoke(BLOInstance, null);
            }
            else
            {
                retVal = mi.Invoke(BLOInstance, argis);
            }

            if (mi.ReturnType == typeof(void))
            {
                return null;
            }
            else
            {
                return Newtonsoft.Json.JsonConvert.SerializeObject(retVal);
            }
        }
    }
}
